package org.example.springcloud.listener;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.nacos.api.config.listener.Listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.Executor;

@Component
@RefreshScope
public class ServiceListener implements Listener {

    @Autowired
    private DruidDataSource dataSource;

    @Autowired
    private DataSourceProperties properties;

    @Override
    public void receiveConfigInfo(String configInfo) {
        //收到新的配置
        System.out.println("receive:" + configInfo);
        System.out.println(properties.toString());


        Properties properties = new Properties();
        InputStream inputStream = new ByteArrayInputStream(configInfo.getBytes());
        try {
            properties.load(inputStream);

            dataSource.setPassword(properties.getProperty("password"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            dataSource.restart();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



    @Override
    public Executor getExecutor() {
        return null;
    }
}
